<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Models\Cruise\CruiseTemplateModel;
use Closure;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

class ConfigModel extends BaseModel
{
    use HasFactory;

    const TYPE_INT        = 'int';
    const TYPE_STRING     = 'string';
    const TYPE_ARRAY      = 'array'; // 未来即将废弃
    const TYPE_JSON       = 'json';

    const TYPE_MAP = [
        self::TYPE_INT        => "整形",
        self::TYPE_STRING     => "字符串",
        self::TYPE_ARRAY      => "数组",
        self::TYPE_JSON       => 'json',
    ];

    const IS_PUBLIC = 1; // 公有的
    const IS_PRIVATE = 0; // 私密的

    protected $table = 'config';

    protected $fillable = [
        'name',
        'module',
        'description',
        'type',
        'value',
        'public',
    ];

    /**
     * name
     */
    const SITE_MANAGER           = 'siteManager';            // 选址管理员
    const SITE_SUPER_ADMIN       = 'siteSuperManager';       // 选址总部负责人
    const SITE_PLACEHOLDER_ADMIN = 'sitePlaceholderManager'; // 预选址负责人
    const FUYOU_SHOP_IMG         = 'fuyouShopImg';           // 富友店铺审核配置图片
    const VERIFY_PERSONNEL       = 'verifyPersonnel';        // 选址核实人员

    const BRAND_TREE             = 'brandTree';  //品牌树


    //MODULE
    const MODULE_WANGGUI = 'wanggui';



    //NAME
    const NAME_STREET_GEO_JSON = 'streetGeojsonFiles';




    public static function getValue(string $module, string $name)
    {
        $query = self::query()->where('module', $module)->where('name', $name)->first();
        if (!$query) {
            return '';
        }

        if ($query->type == self::TYPE_ARRAY) {
            return json_decode($query->value, true);
        }

        return $query->value;
    }




    public static function getValueNewJson(string $module, string $name, int $cacheTtl = 0)
    {
        if ($cacheTtl > 0) {
            return Cache::remember(
                'config:' . $module . ':' . $name,
                $cacheTtl,
                function () use ($module, $name) {
                    return self::getValueNewJson($module, $name, 0);
                }
            );
        }

        $query = self::query()->where('module', $module)->where('name', $name)->first();
        if (!$query) {
            return '';
        }

        if (in_array($query->type, [self::TYPE_ARRAY, self::TYPE_JSON])) {
            return json_decode($query->value, true);
        }

        return $query->value;
    }


    /**
     * 修改value
     * @param string $module
     * @param string $name
     * @param $value
     * @return bool|void
     */
    public static function setValue(string $module, string $name, $value)
    {
        $query = self::query()->where('module', $module)->where('name', $name)->first();
        if (!$query) {
            return;
        }
        $query->value = $value;
        return $query->save();
    }

    /**
     * 获得指定负责人
     * @return mixed
     */
    public static function getManager(string $name)
    {
        return json_decode(self::query()->where('module', 'siteLocation')->where('name', $name)->value('value'), true);
    }

    /**
     * 获得商学院管理员
     * @return mixed
     */
    public static function getCollegeManager()
    {
        return json_decode(self::query()->where('module', 'college')->where('name', 'collegeManager')->value('value'), true);
    }

    /**
     * 获得所有负责人
     * @return array
     */
    public static function getManagerAll(): array
    {
        $manager = [];
        self::query()
            ->where('module', 'siteLocation')
            ->whereIn('name', [ConfigModel::SITE_SUPER_ADMIN, ConfigModel::SITE_MANAGER])
            ->get()
            ->each(function ($item) use (&$manager) {
                $manager = array_merge($manager, json_decode($item->value));
            });
        return $manager;
    }

    /**
     * 获取稽核管理员
     * @param string $companyId
     * @return array
     */
    public static function getCruiseCheckAudit(string $companyId = '', int $templateType = CruiseTemplateModel::TYPE_3, $roleId = FsCompanyRoleMappingModel::ROLE_ID_COMPANY_FIRST) : array
    {
        // 门店稽核 - 负责人
        if ($templateType == CruiseTemplateModel::TYPE_3) {

            if ($companyId) {

                // 专项三方
                $fsCompanyId = (int)FsCompanyModel::query()->where('departmentId', $companyId)->value('id');
                return FsCompanyRoleMappingModel::getCompanyUserIdsByRole($fsCompanyId, $roleId);

            } else {

                // 专项内部 & 常规
                return (array)json_decode(self::query()
                                       ->where('module', 'cruiseCheck')
                                       ->where('name', 'kfAudit')
                                       ->value('value'), true);
            }
        }

        if ($companyId) {
            $name = 'companyAudit_' . $companyId;
        } else {

            if ($templateType == CruiseTemplateModel::TYPE_8) {
                $name = 'kfAudit_8';
            } else {
                $name = 'kfAudit';
            }
        }

        return (array)json_decode(self::query()
                                      ->where('module', 'cruiseCheck')
                                      ->where('name', $name)
                                      ->value('value'), true);
    }

    public static function createCruiseCheckAudit(string $companyId, string $companyName): array
    {
        $query = self::query()->where('module', 'cruiseCheck')->where('name', 'companyAudit_' . $companyId)->first();
        if ($query) {
            return [$query, false];
        }

        return [self::query()->create([
            'module'      => 'cruiseCheck',
            'name'        => 'companyAudit_' . $companyId,
            'description' => "三方-稽核管理员({$companyName})",
            'type'        => self::TYPE_JSON,
            'value'       => '[]'
        ]), true];
    }

    /**
     * 获取单一配置
     *
     * @param string|null $module
     * @param string|null $name
     * @param Closure|null $handleConfigFunc
     * @param int $cacheTime
     * @return mixed
     */
    public static function getSingleConfig(string $module, string $name, Closure $handleConfigFunc = null, int $cacheTime = 0)
    {
        $getConfigFunc = function()use($module, $name){
            return ConfigModel::query()
                              ->where("module", $module)
                              ->where("name", $name)
                              ->first()
                              ->getAttribute("value");
        };


        if($cacheTime > 0){
            $cacheKey = vsprintf(
                "configCache:%s:%s:%s",
                [
                    $module,
                    $name,
                    md5(json_encode(func_get_args(), JSON_UNESCAPED_UNICODE))
                ]
            );
            $configValue = Cache::remember($cacheKey, $cacheTime, $getConfigFunc);
        }else{
            $configValue = $getConfigFunc();
        }
        return $handleConfigFunc ? $handleConfigFunc($configValue) : $configValue;
    }

    /**
     * 获取稽核整改建议配置
     * @return array
     */
    public static function getCruiseApprovalOpinionConfig(): array
    {
        return (array)json_decode(
            self::query()
                ->where('module', 'cruiseCheck')
                ->where('name', 'approvalOpinionConfig')
                ->value('value'), true
        );
    }

    /**
     * 获取稽核巡检图库保存时间（单位：秒）
     */
    public static function getCruiseAlbumExpiredTime(): int
    {
        return self::query()
                ->where('module', 'cruiseCheck')
                ->where('name', 'albumExpiredTime')
                ->value('value') ?? 86400;
    }

    /**
     * 通过appId获取飞书应用配置信息
     * @param string $appId
     * @return array
     */
    public static function getFsConfigByAppId(string $appId): array
    {
        $config = self::fsAppConfig();
        if (!$config) {
            return [
                'appId'        => '',
                'appSecret'    => '',
                'platformName' => '',
            ];
        }

        return [
            'appId'        => $config[$appId]['appId'],
            'appSecret'    => $config[$appId]['appSecret'],
            'platformName' => $config[$appId]['platformName'],
        ];
    }

    /**
     * 通过platformName && orgId 获取飞书应用配置信息
     * @param string $platformName
     * @param int $orgId
     * @return array
     */
    public static function getFsConfigByPlatformNameOrgId(string $platformName, int $orgId = 0): array
    {
        $config = self::fsAppConfig();

        foreach ($config as $val) {
            if ($val['orgId'] == $orgId && $val['platformName'] == $platformName) {
                return [
                    'appId'        => $val['appId'],
                    'appSecret'    => $val['appSecret'],
                    'platformName' => $val['platformName'],
                ];
            }
        }

        return [];
    }

    /**
     * 飞书appid配置大全
     * @return array
     */
    private static function fsAppConfig(): array
    {
        return Cache::remember('getFsConfigByAppId:' . config('app.env'), 60, function () {
            $data = self::query()
                        ->where('module', 'feishu')
                        ->where('name', 'appConfig.' . config('app.env'))
                        ->value('value');

            return json_decode($data, true);
        });
    }

    /**
     * 商增客服灵文销氪配置
     * @return string
     */
    public static function getXiaokeConfig(): string
    {
        return Cache::remember(
            'getXiaokeConfig:' . config('app.env'), 600, function () {
            return self::query()
                    ->where('module', 'xiaoke')
                    ->where('name', 'xiaokeOwerUser')
                    ->value('value') ?? '2974500871';
        }
        );
    }

    /**
     * 分账模式工单自动带入「厦门心有炸念」账号信息（商户号 密钥 前缀）配置
     * @return array
     */
    public static function getFuyouCompanyConfig(): array
    {
        return Cache::remember(
            'getFuyouCompanyConfig:', getSwitchCacheTime(600), function () {
            $data = self::query()
                ->where('module', 'workOrder')
                ->where('name', 'fuyouCompanyConfig')
                ->value('value');
            return $data ? json_decode($data, true) : [];
        }
        );
    }

    /**
     * 富友流程完成自动修改工单开关配置
     * @return array
     */
    public static function getAutoFuyouSwitchConfig(): array
    {
        return Cache::remember(
            'getAutoFuyouSwitchConfig', getSwitchCacheTime(600), function () {
            $data = self::query()
                ->where('module', 'workOrder')
                ->where('name', 'getAutoFuyouSwitchConfig')
                ->value('value');
            return $data ? json_decode($data, true) : [];
        }
        );
    }
    /**
     * 订货开票邮箱开关配置
     * @return array
     */
    public static function getOrderGoodsEmailConfig():array
    {
        return Cache::remember(
            'getOrderGoodsEmailConfig', getSwitchCacheTime(600), function () {
            $data = self::query()
                ->where('module', 'kfos.invoice')
                ->where('name', 'order_goods_email_v2')
                ->value('value');
            return $data ? json_decode($data, true) : [];
        }
        );
    }

    public static function getShopAdsConfig():array
    {
        if(isTest()){
            $data = self::query()
                       ->where('module', 'shop.advertise')
                       ->where('name', 'config')
                       ->value('value');
            return $data ? json_decode($data, true) : [];
        }

        return Cache::remember(
            'getShopAdsConfig', getSwitchCacheTime(600), function () {
            $data = self::query()
                        ->where('module', 'shop.advertise')
                        ->where('name', 'config')
                        ->value('value');
            return $data ? json_decode($data, true) : [];
        });
    }


}
